package com.h3bpm.starcharge.controller;

import OThinker.Common.DotNetToJavaStringHelper;
import OThinker.Common.Organization.Models.OrganizationUnit;
import OThinker.H3.Controller.ControllerBase;
import com.h3bpm.base.util.AppUtility;
import com.h3bpm.starcharge.common.uitl.DataTableUtil;
import data.DataRow;
import data.DataTable;
import net.sf.json.JSONArray;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author : Coco
 * @Description : 标准销售合同
 * @Date : Create in 15:54 2019/1/4
 * @Modified :
 */
@Controller
@RequestMapping("/starCharge/standardSaleController")
public class StandardSaleController extends ControllerBase{

    final static String COMPANY_ID = "18f923a7-5a5e-426d-94ae-a55ad1a4b240";// 公司id

    @Override
    public String getFunctionCode() {
        return null;
    }

    @ResponseBody
    @RequestMapping(value = "/getSaleApproval", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String getSaleApproval(@RequestParam("modelStr") String modelStr, @RequestParam("priceStr") String priceStr
    , @RequestParam("originatorOU") String originatorOU, @RequestParam("originatorId") String originatorId) throws Exception {
        DataTable dt = null;

        // 结果集
        Map<String, String> result = new HashMap<>();

        // 先递归获取发起人所在部门并存储
        Map<String, String> rDepTree = new LinkedHashMap<>();
        int i = 1;
        rDepTree.put(i+"",originatorOU);
        String parentDepId = originatorOU;
        while ((parentDepId = StringUtils.trimToNull(this.getParentOU(parentDepId))) != null) {
            rDepTree.put(++i + "",parentDepId);
        }

        // 审批机构map集合
        Map<String, String> depTree = new LinkedHashMap<>();
        // 一共有三级审批，截取map的后三个数据即可    1：区总；2：省总；3：市总
        int num = 0;
        for (int j = rDepTree.size(); j >= 0; j--) {
            depTree.put(++num +"", rDepTree.get(j +""));
            if (num == 3) {
                break;
            }
        }

        // 由设备信息子表的单价和型号获取最高审批级别
        String approvalLevel = this.getSaleTopLevel(modelStr, priceStr);

        // 审批部门所在级别
        String oULevel = "";
        // 审批部门所在级别对应负责人
        String levelApproval = "";
        // 审批级别对应的部门id
        String approvalOUId = depTree.get(approvalLevel);
        if ("1".equals(approvalLevel)){
            oULevel = "OUIdFirst";
            levelApproval = "ApprovalFirst";
        } else if ("2".equals(approvalLevel)){
            oULevel = "OUIdSecond";
            levelApproval = "ApprovalSecond";
        } else {
            oULevel = "OUIdThird";
            levelApproval = "ApprovalThird";
        }
        String approvalSql = "SELECT "+ levelApproval +" approval FROM I_approvalSales WHERE "+ oULevel +" = '%s'";
        DataTable dataTable = DataTableUtil.getDataTable(approvalSql, approvalOUId);
        if (dataTable.getRows().size() != 0) {
            if (!"1".equals(approvalLevel) && dataTable.getRows().get(0).getString("approval").equals(originatorId)) {
                approvalLevel = Integer.valueOf(Integer.valueOf(approvalLevel) - 1).toString();
                approvalOUId = depTree.get(approvalLevel);
                if ("1".equals(approvalLevel)){
                    oULevel = "OUIdFirst";
                    levelApproval = "ApprovalFirst";
                } else {
                    oULevel = "OUIdSecond";
                    levelApproval = "ApprovalSecond";
                }
                approvalSql = "SELECT "+ levelApproval +" approval FROM I_approvalSales WHERE "+ oULevel +" = '%s'";
                DataTable dataTable3 = DataTableUtil.getDataTable(approvalSql, approvalOUId);
                if (dataTable3.getRows().size() != 0){
                    result.put("approval",dataTable3.getRows().get(0).getString("approval"));
                    return JSONArray.fromObject(result).toString();
                } else {// 出现这种情况当且仅当三级、二级审批人均无
                    approvalSql = "SELECT ApprovalFirst approval FROM I_approvalSales WHERE OUIdFirst = '%s'";
                    DataTable dataTable4 = DataTableUtil.getDataTable(approvalSql, depTree.get("1"));
                    if (dataTable4.getRows().size() != 0){
                        result.put("approval",dataTable4.getRows().get(0).getString("approval"));
                        return JSONArray.fromObject(result).toString();
                    }
                }
            }
            result.put("approval",dataTable.getRows().get(0).getString("approval"));
            return JSONArray.fromObject(result).toString();
        } else {
            if (!"1".equals(approvalLevel)){
                // 如果没有获得则取上级机构审批人
                approvalLevel = Integer.valueOf(Integer.valueOf(approvalLevel) - 1).toString();
                approvalOUId = depTree.get(approvalLevel);
                if ("1".equals(approvalLevel)){
                    oULevel = "OUIdFirst";
                    levelApproval = "ApprovalFirst";
                } else if ("2".equals(approvalLevel)){
                    oULevel = "OUIdSecond";
                    levelApproval = "ApprovalSecond";
                } else {

                }
                approvalSql = "SELECT "+ levelApproval +" approval FROM I_approvalSales WHERE "+ oULevel +" = '%s'";
                DataTable dataTable2 = DataTableUtil.getDataTable(approvalSql, approvalOUId);
                if (dataTable2.getRows().size() != 0){
                    return dataTable2.getRows().get(0).getString("approval");
                } else {
                    // 出现这种情况当且仅当三级、二级审批人均无
                    approvalSql = "SELECT ApprovalFirst approval FROM I_approvalSales WHERE OUIdFirst = '%s'";
                    DataTable dataTable3 = DataTableUtil.getDataTable(approvalSql, depTree.get("1"));
                    if (dataTable3.getRows().size() != 0){
                        result.put("approval",dataTable3.getRows().get(0).getString("approval"));
                        return JSONArray.fromObject(result).toString();
                    }
                }
            }
        }
        return null;
    }

    private String getSaleTopLevel(String modelStr, String priceStr) throws Exception{

        String[] modelArr = modelStr.split(";");
        String[] priceArr = priceStr.split(";");
        String sql = "SELECT authorityArea, authorityProvince, authorityCity FROM I_productList WHERE model = '%s'";

        //默认审批级别
        String approvalLevel = "3";

        for (int i = 0; i < modelArr.length; i++) {

            // 先判断审批级别是否是第一级，如果是，子表没有必要循环下去
            if ("1".equals(approvalLevel)) {
                return approvalLevel;
            } else {
                DataTable dataTable = DataTableUtil.getDataTable(sql,modelArr[i]);
                double price = 0.0;
                if (StringUtils.trimToNull(priceArr[i]) != null) {
                    price = Double.valueOf(priceArr[i]);
                }

                if (dataTable.getRows().size() > 0) {
                    DataRow dataRow = dataTable.getRows().get(0);
                    double authorityProvincePrice = Double.valueOf(dataRow.getString("authorityProvince"));
                    double authorityCityPrice = Double.valueOf(dataRow.getString("authorityCity"));

                    if (price != 0.0) {
                        // 预防前台传过来的价格为空
                        if (price < authorityProvincePrice) {
                            approvalLevel = "1";
                        } else if (price < authorityCityPrice && price >= authorityProvincePrice) {
                            approvalLevel = "2";
                        } else {
                            // 否则为“3”级审批，已默认
                        }
                    }
                }
            }
        }
        return approvalLevel;
    }

    /**
     * 获取父部门
     * @param oUId
     * @return
     * @throws Exception
     */
    public String getParentOU(String oUId) throws Exception {
        String sql = "SELECT ParentID FROM OT_OrganizationUnit WHERE ObjectID = '%s'";
        DataTable dataTable = DataTableUtil.getDataTable(sql, oUId);
        if (dataTable.getRows().size() != 0) {
            String id = StringUtils.trimToNull(dataTable.getRows().get(0).getString("ParentID"));
            if (!COMPANY_ID.equals(id) && id != null) {
                return id;
            }
        }
        return null;
    }

    /**
     * 获取上两级领导
     * @param OUId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/getParentInfo", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String getParentInfo(@RequestParam("OUId")String oUId) throws Exception {

        // 结果集
        Map<String, String> result = new HashMap<>();

        Map<String, String> ouMap = new HashMap<>();;
        ouMap.put("ManagerID","");
        ouMap.put("parentOUId","");

            String nowOUId = oUId;
            // 部门向上遍历，直至到找有经理的部门，和该部门的上级部门
            while (DotNetToJavaStringHelper.isNullOrEmpty(ouMap.get("ManagerID")) && !COMPANY_ID.equals(nowOUId)){
                OrganizationUnit nowOU  = (OrganizationUnit)AppUtility.getEngine().getOrganization().GetUnit(nowOUId);
                //部门负责人不是自己
                if (!this.getUserValidator().getUserID().equals(nowOU.getManagerID())) {
                    ouMap.put("ManagerID",nowOU.getManagerID());
                }

                nowOUId = nowOU.getParentID();
                ouMap.put("parentOUId",nowOUId);
            }
            result.put("thisLeader",ouMap.get("ManagerID"));

            ouMap.put("ManagerID","");
            // 部门向上遍历，直至到找有经理的部门，和该部门的上级部门
            while ((DotNetToJavaStringHelper.isNullOrEmpty(ouMap.get("ManagerID")) || result.get("thisLeader").equals(ouMap.get("ManagerID"))) && !COMPANY_ID.equals(nowOUId)){
                OrganizationUnit nowOU  = (OrganizationUnit)AppUtility.getEngine().getOrganization().GetUnit(nowOUId);
                //部门负责人不是自己
                if (!this.getUserValidator().getUserID().equals(nowOU.getManagerID())) {
                    ouMap.put("ManagerID",nowOU.getManagerID());
                }
                nowOUId = nowOU.getParentID();
                ouMap.put("parentOUId",nowOUId);
            }
           result.put("upLeader",ouMap.get("ManagerID"));
           return JSONArray.fromObject(result).toString();
    }

    /**
     * 获取父部门id和主管
     * @param oUId 部门id
     * @return
     * @throws Exception
     */
    private Map<String, String> getOUManageId(String oUId) throws Exception{

        if (COMPANY_ID.equals(oUId)) {
            return null;
        } else {
            Map<String, String> result = new HashMap<>();
            String sql = "SELECT ManagerID, ParentID FROM OT_OrganizationUnit WHERE ObjectID = '%s'";
            DataTable dataTable = DataTableUtil.getDataTable(sql, oUId);
            if (dataTable.getRows().size() > 0) {
                DataRow dataRow = dataTable.getRows().get(0);
                if (StringUtils.trimToNull(dataRow.getString("ManagerID")) == null) {
                    result.put("ManagerID","");
                } else {
                    result.put("ManagerID",dataRow.getString("ManagerID"));
                }
                if (StringUtils.trimToNull(dataRow.getString("ParentID")) == null) {
                    result.put("ParentID","");
                } else {
                    result.put("ParentID",dataRow.getString("ParentID"));
                }
                return result;
            }
            return null;
        }
    }
}
